package rs.mbs2.epics.server.servlet;

import java.io.IOException;
import java.util.Date;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import rs.mbs2.epics.server.entity.Album;
import rs.mbs2.epics.server.entity.Comment;
import rs.mbs2.epics.server.entity.Photo;
import rs.mbs2.epics.server.entity.User;
import rs.mbs2.epics.server.servlet.util.Emailer;
import rs.mbs2.epics.server.servlet.util.Validation;
import rs.mbs2.epics.server.session.dao.localinterface.AlbumDaoLocal;
import rs.mbs2.epics.server.session.dao.localinterface.CommentDaoLocal;
import rs.mbs2.epics.server.session.dao.localinterface.PhotoDaoLocal;
import rs.mbs2.epics.server.session.dao.localinterface.UserDaoLocal;

@SuppressWarnings("serial")
public class PostCommentController extends HttpServlet {
	
	private static Logger log = Logger.getLogger(CreateAlbumController.class);

	
	@EJB
	private PhotoDaoLocal photoDao;
	
	@EJB
	private UserDaoLocal userDao;
	
	@EJB
	private CommentDaoLocal commentDao;
	
	@EJB
	private AlbumDaoLocal albumDao;
	
	@Resource(name="Mail")
	private Session session;
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		System.out.println("PostCommentController.doGet()");
		
		String photoIdStr = request.getParameter("photoId");
		int photoId = Integer.parseInt(photoIdStr);
		
		String commentText = request.getParameter("commentText");		
		String commentTitle = request.getParameter("commentTitle");
		
		boolean isValid = true;		
		isValid = Validation.validateString(commentText);
		
		if(isValid)
		isValid = Validation.validateString(commentTitle);
		
		if(!isValid) {
			log.info(new Date() + ": Uneti nevalidni podaci u komentarisanju slike.");
			response.sendRedirect(response.encodeRedirectURL("./viewPhoto.jsp"));
			return;
		}

		User loggedUser = (User) request.getSession().getAttribute("user");
		User user = userDao.findById(loggedUser.getId());
		
		Photo photo = photoDao.findById(photoId);
		
		Comment postedComment = new Comment(commentTitle,commentText, new Date(), user, photo);
		commentDao.persist(postedComment);
		
		Album album = (albumDao.findAlbumsByPhotoId(photoId)).get(0);
		//if(!a.getTitle().equals(""))	// TODO: provera da nije favourite album u pitanju
		User photoOwner = userDao.findUserThatCreatedAlbum(album.getId());
		if(photoOwner.getEmailNotifications()) {
			
			try {

				System.out.println("PostCommentController.doGet()");
				System.out.println("******************************");
				System.out.println("Null: " + session == null);
				System.out.println(photoOwner.getEmailAddress());
				System.out.println("******************************");
				
				Emailer emailer = new Emailer();
				emailer.sendMessage(session, "mbs2testmail@gmail.com", photoOwner.getEmailAddress());
				
				System.out.println("MESSAGE BEAN: Mail was sent successfully.");
			} catch (AddressException e) {
				e.printStackTrace();
			} catch (MessagingException e) {
				e.printStackTrace();
			}

			
			
			
			/*
			Emailer emailer = new Emailer();
			
			try {
				emailer.sendMessage(session, loggedUser.getEmailAddress(), photoOwner.getEmailAddress());
				System.out.println("PostCommentController.doGet()");
				System.out.println("*****************************");
				System.out.println("Email uspesno poslat");
				System.out.println("*****************************");
			} catch (AddressException e) {
				e.printStackTrace();
			} catch (MessagingException e) {
				e.printStackTrace();
			}
			
			boolean emailSent = emailer.sendEMail(photoOwner);
			if(emailSent) {
				log.info("E mail je poslat.");
			}*/
		}
			
		
		log.info(new Date() + ": Dodat komentar: " + commentText  + "  na sliku id: " + photoId + "  (USER ID: " + user.getId() + ")");		
		getServletContext().getRequestDispatcher("/ViewPhotoController?id=" + photoId).forward(request, response);

	}
	

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}


}
